package com.mobi.cacti.rabbit.controllers;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;

import com.mobi.cacti.rabbit.connectors.AbstractServerConnector;
import com.mobi.cacti.rabbit.connectors.NewsAndPromotionServerConnector;
import com.mobi.cacti.rabbit.connectors.ServerConnectorCallback;
import com.mobi.cacti.rabbit.response.Cache;
import com.mobi.cacti.rabbit.response.ReqRssItem;
import com.mobi.cacti.rabbit.response.ReqTicketDetail;
import com.mobi.cacti.rabbit.utils.SAXXMLParser;

public class NewsAndPromotionListActivityViewController implements ServerConnectorCallback{
	
	private NewsAndPromotionServerConnector newsServerConnector;
	private NewsAndPromotionServerConnector promotionServerConnector;
	
	public NewsAndPromotionListActivityViewControllerCallback delegate;
	private static NewsAndPromotionListActivityViewController instance = null;

	public static NewsAndPromotionListActivityViewController getInstance() {
		if(instance == null) {
			instance = new NewsAndPromotionListActivityViewController();
		}
		return instance;
	}
	
	public void loadNews(Context context)
	{
		if(!Cache.isNetworkAvailable(context))
		{
			Cache.showNoInternetAlertDialog(context);
			return ;
		}
		
		newsServerConnector = new NewsAndPromotionServerConnector();
		newsServerConnector.delegate = this;
		newsServerConnector.loadNews();
	}
	
	public void loadPromotion(Context context)
	{
		if(!Cache.isNetworkAvailable(context))
		{
			Cache.showNoInternetAlertDialog(context);
			return ;
		}

		promotionServerConnector = new NewsAndPromotionServerConnector();
		promotionServerConnector.delegate = this;
		promotionServerConnector.loadPromotion();
	}

	@Override
	public void serverConnectorFinishBackgroundTask(
			AbstractServerConnector serverConnector, Object response) {
		
		Log.i("tai", "XML raw = "+response);
		
		InputStream is = new ByteArrayInputStream(((String) response).getBytes());
		ArrayList<ReqRssItem> rssItems = SAXXMLParser.respRssItem(is);
		
		Log.i("tai","RSS count = "+rssItems.size());

		if(serverConnector == newsServerConnector)
		{
			delegate.newsAndPromotionListActivityControllerFinishLoadNews(rssItems);
		}
		else if(serverConnector == promotionServerConnector)
		{
			delegate.newsAndPromotionListActivityControllerFinishLoadPromotion(rssItems);
		}
	}

}
